package com.ysm.smfu.activity;

import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.bean.VersionInfo;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.NotificationUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.FlashActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class AboutActivity extends BaseActivity {

    @BindView(R.id.about_curVersion)
    TextView about_curVersion;
    private int versionCode;
    private String versionName;
    private NotificationUtil notificationUtil;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_about);
        ButterKnife.bind(this);
        getVersionCode();
    }

    @OnClick({R.id.about_testV, R.id.about_oldV, R.id.about_goJudge, R.id.back})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.about_testV:
                goTestVersion();
                break;
            case R.id.about_oldV:
                goHistoryPage();
                break;
            case R.id.about_goJudge:
//                去评分
                goJudge();
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    /**
     * 获取版本号和版本名
     */
    private void getVersionCode() {
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;
            versionCode = packageInfo.versionCode;
            about_curVersion.setText("当前版本:" + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳往历史版本页面
     */
    private void goHistoryPage() {
        UIUtils.startActivity(HistoryVersionActivity.class);
    }

    /**
     * 检测新版本
     */
    private void goTestVersion() {
        BaseProtocal.builder(false).checkVersion(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("历史版本", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    VersionInfo versionInfo = new Gson().fromJson(response, VersionInfo.class);
                    List<VersionInfo.HistoryVersionInfo> historyVersionInfos = versionInfo.versionInfo;
                    dealVersion(historyVersionInfos.get(0));
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast("网络繁忙，请稍后重试");
            }
        }, 1, 1);
    }

    /**
     * 处理版本信息
     *
     * @param historyVersionInfo
     */
    private void dealVersion(VersionInfo.HistoryVersionInfo historyVersionInfo) {
        if (Integer.parseInt(historyVersionInfo.appVersionCode) <= versionCode) {
            showMsg(versionName + "已是最新版本");
            return;
        } else {
            showUpdateDialog(historyVersionInfo.appVersionName, historyVersionInfo.appDescribe);
        }
    }

    public void showMsg(String msg) {
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("更新提示")
                .setMessage(msg)
                .setPositiveButton("确定", null)
                .create();
        dialog.show();
    }

    /**
     * 去应用市场评分
     */
    private void goJudge() {
        try {
            Uri uri = Uri.parse("market://details?id=" + getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastUtils.showToast("没有找到应用市场");
        }
    }


    /**
     * 更新对话框
     */
    private void showUpdateDialog(String version, String msg) {

        final AlertDialog.Builder adb = new AlertDialog.Builder(AboutActivity.this);
        adb.setTitle("发现新版本 " + version);
//        最新版本描述
        adb.setMessage(msg);

        adb.setPositiveButton("下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 下载APK
                downLoadApk();
            }
        });

        adb.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // 点击后退按键，取消对话框时，调用
        adb.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
            }
        });
        adb.show();
    }

    /**
     * 下载更新APK
     */
    protected void downLoadApk() {

        // 判断SD卡是否存在
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            ToastUtils.showToast(this, "没有发现SD卡，无法下载");
            return;
        }
        // 下载路径为 sd 卡根目录下的 .apk 文件
        final String target = Environment.getExternalStorageDirectory().getAbsolutePath() + "/dmh";
        if (notificationUtil == null)
            notificationUtil = new NotificationUtil(this);
        notificationUtil.showNotification(100);
        OkHttpUtils.get().url(SpKey.LOADAPK)
                .build()
                .execute(new FileCallBack(target, "dmh.apk") {
                             @Override
                             public void inProgress(float progress, long total, int id) {
                                 super.inProgress(progress, total, id);
                                 notificationUtil.updateProgress(100, progress);
                             }

                             @Override
                             public void onError(Call call, Exception e, int id) {
                                 ToastUtils.showToast("网络异常,请稍后重试");
                                 notificationUtil.cancel(100);
                             }

                             @Override
                             public void onResponse(File response, int id) {
                                 notificationUtil.cancel(100);
//                                 安装apk
                                 Intent intent = new Intent();
                                 intent.setAction("android.intent.action.VIEW");
                                 intent.addCategory("android.intent.category.DEFAULT");
                                 File apkFile = new File(target, "dmh.apk");
                                 intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                                 startActivityForResult(intent, 88);
                             }
                         }
                );
    }

    /**
     * 当在安装APK的页面，点击取消时，执行此方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 88 && requestCode == FlashActivity.RESULT_OK) {
//            用户安装了安装新的anpk

        } else if (requestCode == 88 && requestCode == FlashActivity.RESULT_CANCELED) {
//           用户取消了安装
        }
    }
}
